<!--
 * @description  : 物品信息登记
 * @descriptionDetail: 物品信息登记
 * @copyright    : 广西烟草
 * @author       : wmb
 * @create       : 2022-07-09 18:43:02
-->
<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar :is-white="false" :title="navTitle" :custom-back="goBack" style="z-index: 99999">
      <view class="nav-right-icon" v-if="canRollBack" @tap="rollBack">
        恢复数据
      </view>
    </theme-navbar>
    <!-- #endif -->
		<!-- #ifdef H5-WECHAT || H5-EMP -->
		<fab-button :content="fContent" @fabtrigger="fabtrigger" v-if="canRollBack" />
		<!-- #endif -->
		<view class="content content-bg ifn-content u-padding-30" style="background-color: white;">
			<view class="sub-title-lay">
				<view class="sub-title">
					案件编号
				</view>
				<text>{{ caseCode }}</text>
			</view>
			<view class="u-flex search-lay">
				<view class="search-title">
					品种及规格
				</view>
				<view class="u-flex">
					<view style="position: relative; padding-right: 20rpx;">
						<input style="position: absolute;top: 8px;left: 4px;" class="u-input__input" type="text" placeholder="请输入关键字" placeholderStyle="'color: #c0c4cc;'" :focus="scanOtherShow" confirmType="done" :cursor-spacing="0" :show-confirm-bar="true" v-show="scanOtherShow" id="scanOther" v-model="hideVal" @input="scanOtherInputEvent" />
						<u-input :custom-style="customStyle" placeholder="请输入关键字" :focus="focus" :disabled="scanOtherShow" v-model="searchTxt" @blur="searchBlur" @focus="searchFocus">
						</u-input>
					</view>
					<view class="u-m-l-10">
						<u-icon name="scan" color="primary" size="48" @click="scanClick"></u-icon>
					</view>
				</view>
			</view>
			<u-line class="u-m-t-15 u-m-b-15 good-search-line" :color="$theme['u_border_color']"></u-line>
			<view class="good-search-lay" :style="{top: searchGoodTop,height: searchGoodHeight}" v-if="showSearchGoods" @touchstart="touchStart" @touchend="touchEnd">
				<scroll-view scroll-y="true" :style="{height: searchGoodHeight}">
					<u-cell-group>
						<u-cell-item :titleStyle="{fontSize: '32rpx',}" :title="item.productName + ' ' + (item.stripCode || '') + ' , ' + (getItemActiveStatus(item.isActive))" :arrow="true" v-for="item in searchGoodList" :key="item.productUuid" @click="choiceGoodItem(item)">
						</u-cell-item>
					</u-cell-group>
				</scroll-view>
			</view>
			<view :style="{height: getListHeight()}">
				<me-list :normalScrollView="false" :i="0" idKey="goodsRdmUuid" :initiativeTap="true" :limit="limit" :height="getListHeight()" :loadData="loadData" ref="mescrollRef0">
					<view slot-scope="d" style="width: 100%;">
					<!-- 2024-01-09 处理来源地、去向地下拉框选项超出被隐藏的bug ljb start  -->
					<u-swipe-action :show="d.data.show" :index="d.data.goodsRdmUuid" :disabled="d.data.swiperDisabled" @click="swiperClick" @open="swiperOpen" :options="swiperOptions" :style="{overflow: 'scroll'}">
						<!-- 2024-01-09 处理来源地、去向地下拉框选项超出被隐藏的bug ljb start -->
							<view class="lay-item">
								<view class="num-lay">
									<view class="num-title">
										{{ getIndexByGoodsList(d.data.goodsRdmUuid) }}
									</view>
									<view class="num-content">
										<good-input type="text" :customStyle="(d.data.innerProductType == '01' || d.data.innerProductType == '02') ? cusStyle : {}" placeholder="" :disabled="isDisable(d.data)" :extStr="d.data.goodsRdmUuid" v-model="d.data.goodsName" @input="inputGNameEvent"></good-input>
									</view>
								</view>
								<view class="u-flex">
									<view class="u-flex-1 pty-lay">
										<view>数量：</view>
										<good-input type="digit" class="u-m-l-20 u-m-r-20" :customStyle="cusStyle" inputAlign="right" placeholder="请输入" :extStr="d.data.goodsRdmUuid" v-model="d.data.qty" :numberFixed="1" @input="inputQtyEvent"></good-input>
										<view>{{ d.data.unit }}</view>
									</view>
									<view class="u-flex-1 price-lay">
										<view>单价：</view>
										<good-input type="digit" class="u-m-r-20" :customStyle="cusStyle" inputAlign="right" placeholder="请输入" :extStr="d.data.goodsRdmUuid" v-model="d.data.price" :numberFixed="2" @input="inputPriceEvent"></good-input>
										<view>元/{{ d.data.unit }}</view>
									</view>
								</view>
								<view class="u-flex">
									<view class="u-flex-1 pty-lay">
										<view>支每条 ：</view>
										<good-input type="digit" class="u-m-l-20 u-m-r-20" :customStyle="cusStyle" inputAlign="right" placeholder="请输入" :extStr="d.data.goodsRdmUuid" v-model="d.data.unitQty" :numberFixed="0" @input="inputUnitEvent"></good-input>
										<view>支</view>
									</view>
									<view class="u-flex-1 price-lay">
										<view>金额：</view>
										<u-input type="digit" :disabled="true" class="u-m-l-20 u-m-r-20" :customStyle="cusStyle" inputAlign="right" placeholder="请输入" v-model="d.data.amt">
										</u-input>
										<view>元</view>
									</view>
								</view>
								<u-form-item label-width="auto" v-if="hasShowChoicePropSubType(d.data.goodsType)" :label-style="labelStyle" class="u-m-l-10" label="物品性质:">
									<dic-input :keyWord="$u.dic.DIC_KEYS.GOODS_PROP_SUBTYPE" :dicCode="d.data.propSubtype" :border="false" inputAlign="right" type="select" :select-open="dicSelectOpen($u.dic.DIC_KEYS.GOODS_PROP_SUBTYPE)" placeholder="请选择" :timeKey="d.data.goodsRdmUuid" v-model="d.data.propSubTypeName" @changeInputModelData="(name)=>{ $set(d.data, 'propSubTypeName', name) }" @click="showDic($u.dic.DIC_KEYS.GOODS_PROP_SUBTYPE,d.data.propSubtype,d.data.goodsRdmUuid)" />
								</u-form-item>
								<u-form-item label-width="auto" :label-style="labelStyle" class="u-m-l-10" label="环节:">
									<dic-input :keyWord="$u.dic.DIC_KEYS.GET_NODE" :dicCode="d.data.getNode" :border="false" inputAlign="right" type="select" :select-open="dicSelectOpen($u.dic.DIC_KEYS.GET_NODE)" placeholder="请选择" :timeKey="d.data.goodsRdmUuid" v-model="d.data.getNodeName" @changeInputModelData="(name)=>{$set(d.data, 'getNodeName', name)}" @click="showDic($u.dic.DIC_KEYS.GET_NODE,d.data.getNode,d.data.goodsRdmUuid)" />
								</u-form-item>
                <u-form-item label-width="auto" :label-style="labelStyle" class="u-m-l-10" label="是否散支烟:">
                  <u-switch
                      style="text-align: right"
                      v-model="d.data.isLooseCigarette"
                  ></u-switch>
                </u-form-item>

								<u-form-item :class="['FT'+d.data.goodsRdmUuid]" label-width="auto" :label-style="labelStyle" class="u-m-l-10" label="来源地:">
									<auto-input tplClass="tp-class" :extStr="d.data.goodsRdmUuid" :absIndex="d.data.goodsRdmUuid" :searchData="searchData" :absClass="'FT'+d.data.goodsRdmUuid" :customStyle="{'textAlign':'right'}" placeholder="请输入来源地" v-model="d.data.sourceAddrName" @choiceAutoItem="choiceAutoItem" @blur="vaildChoice">
									</auto-input>
								</u-form-item>
								<u-form-item :class="['TT'+d.data.goodsRdmUuid]" label-width="auto" :label-style="labelStyle" class="u-m-l-10" label="去向地:">
									<auto-input tplClass="tp-class" :extStr="d.data.goodsRdmUuid" :absIndex="d.data.goodsRdmUuid" :searchData="searchData" :absClass="'TT'+d.data.goodsRdmUuid" :customStyle="{'textAlign':'right'}" placeholder="请输入去向地" v-model="d.data.toAddrName" @choiceAutoItem="choiceAutoItem1" @blur="vaildChoice1">
									</auto-input>
								</u-form-item>
							</view>
						</u-swipe-action>
					</view>
				</me-list>
			</view>
		</view>
		<view class="submit-btns btn-other-cls">
			<u-button class="u-btn" type="primary" @click="confirm">
				确定
			</u-button>
		</view>
		<dic-choice :keyWord="dicKeyWords" :currentSelect="dicCurrentSelect" :extFilterFun="extFilterFun" v-model="dicShow" :needForce="true" @confirm="selectDicConfirm"></dic-choice>
		<u-mask :show="scanOtherShow" @click="hideMask">
			<view class="warp" style="text-align: center;">
				数据录入中,请勿触屏<br>触屏将结束录入
			</view>
		</u-mask>
	</view>
</template>

<script>
	import {
		getPropSubtypesByBrandSubType,
	} from "@/service/case/mapping/propSubtype.js";
	import mescrollList from "@/components/mescroll_list.vue";
	import DicChoice from "@/components/dic_choice.vue";
	import DicInput from "@/components/dic_input.vue";
	import caseService from "@/service/case/case.service";
	import goodInput from "../components/goodInput.vue";
	import AutoInput from "@/components/autoInput.vue";
	import commonService from "@/service/common/common.service.js";
	import {
		goodsService,
	} from "@/sql/case/offlineDataServiceMixins";
	import {
		v4 as uuidv4,
	} from 'uuid';
	import {
		Queue,
	} from "@/common/util.js";
	import fabButton from '@/components/uni-fab.vue';

	export default {
		components: {
			"me-list": mescrollList,
			"dic-choice": DicChoice,
			"dic-input": DicInput,
			goodInput,
			AutoInput,
			fabButton
		}, //
		data() {
			return {
				user: this.$store.state.userInfo,
				caseCode: "",
				caseUuid: "",
				limit: 20,
				hideVal: "",
				dicShow: false, // dic_select 是否显示
				dicKeyWords: "", // dic 关键字
				dicCurrentSelect: "", // dic 当前选择项
				currIndex: 0,
				searchTxt: "",
				labelStyle: {
					fontSize: '30rpx',
				},
				customStyle: {
					backgroundColor: this.$theme['u_bg_color'],
					borderRadius: '20px',
					paddingLeft: '10px',
					paddingRight: '10px',
				},
				cusStyle: {
					color: '#FF943E',
				},
				dataList: [],
				showSearchGoods: false,
				searchFlag: false, // 快慢问题
				searchGoodList: [],
				searchGoodTop: "",
				searchGoodHeight: "",
				preObj: {}, // 上一次的数据, 用于给下一次新增的数据填充默认值
				focus: false,
				defaultWindowHeight: this.$u.sys().windowHeight,
				localData: {},
				showSoftInputView: false,
				tmpChoice: undefined,
				scanOtherShow: false, //  扫码枪状态
				scanOtherData: {}, // 扫码的到的数据集合
				addFrom: "search", // 默认 search  scanBar  infraredScan
				scanVal: undefined,
				interfaceParam: {},
				showAll: false,
				canRollBack: false, // 是否可以恢复数据
				swiperOptions: [{
					text: '删除',
					style: {
						backgroundColor: this.$theme.u_type_error,
					},
				}, ],
				fContent: [{
					iconPath: require('@/static/recover.png'),
					selectedIconPath: require('@/static/recover.png'),
					text: '恢复数据',
					active: false,
				}],
			}
		},
		computed: {
			realDataList() {
				let tmpList = this.dataList.filter(item => {
					return this.$u.test.isEmpty(item.goodsRegUuid);
				});
				tmpList.reverse();
				return tmpList;
			},
		},
		watch: {
			searchTxt(newVal, oldVal) {
				this.$u.debounce(this.getSearchGoodList, 500);
			},
			canRollBack(newVal, oldVal) {
				this.setRightBtns();
			},
		},
		onLoad(opt) {
			let opo = this.getRouteParam() || {};
			this.interfaceParam = opo.params;
			this.showAll = opo.showAll;
			this.caseCode = opt.caseCode;
			this.caseUuid = opt.caseUuid;
			this.localData.caseCode = this.caseCode;
			this.localData.userId = this.user.user.personUuid;
			this.initGoodList();
		},
		mounted() {
			this.init();
		},
		onUnload() {
			uni.offWindowResize(() => {
				console.log('取消监听窗口尺寸变化事件')
			})
		},
		methods: {
			initGoodList() {
				let param = {
					...this.interfaceParam,
				};
				param.isAll = this.showAll ? "1" : "0";
				this.$modal.showLoading('正在加载数据...');
				caseService.caseGoodsList(param).then(res => {
					this.$modal.hideLoading();
					if (res.success) {
						let tmpList = this.$u.deepClone(res.data);
						tmpList.forEach(itm => {
							itm.goodsRdmUuid = itm.goodsDtlUuid;
							itm.checkResult = itm.checkResult || "false";
							itm.show = false;
							itm.swiperDisabled = false;
						});
						if (this.interfaceParam.justUnUse == 'true') { // 在先保书中只有未北使用的数据才会显示
							this.dataList = [...tmpList.filter(itm => {
								return this.$u.test.isEmpty(itm.goodsRegUuid);
							}), ];
						} else {
							this.dataList = [...tmpList, ];
						}
						this.$refs['mescrollRef0'].resetList(false);
						if (this.dataList.length > 0) {
							this.updatePreObj(this.dataList[this.dataList.length - 1]);
						} else {
							this.preObj = undefined;
						}
						this.loadLocal();
					} else {
						this.$modal.alert(res.msg, () => {
							uni.navigateBack();
						});
					}
				}).catch(err => {
					console.log(err);
					this.$modal.hideLoading();
					this.$modal.alert("获取物品数据失败", () => {
						uni.navigateBack();
					});
				});
			},
			getItemActiveStatus(isActive) {
				if (isActive == 1) {
					return "启用";
				} else if (isActive == 2) {
					return "待启用";
				} else if (isActive == 3) {
					return "待引入";
				}
				return "";
			},
			hasShowChoicePropSubType(goodsType) {
				try {
					return goodsType.indexOf('1') == '0' || goodsType.indexOf('7') == '0'; // 类型是1开始的才能设置物品性质,7为电子烟
				} catch (e) {
					console.log(e);
					return true;
				}
			},
			loadLocal() {
				goodsService.getGoodsDb(this.caseCode, this.user.user.personUuid).then(res => {
					if (res) {
						this.canRollBack = true;
						if (uni.getStorageSync("showRollBackDataTip") == '1') return;
						this.$modal.confirm("检测到您上次退出后，存在未提交的数据，是否立即恢复?(您也可点击右上角'恢复数据'按钮来恢复, 继续修改当前页面物品数据将视作放弃数据恢复)", "提示", () => {
							this.localData.content = res.content;
							this.localData.tid = res.tid;
							let tmpList1 = this.$u.deepClone(res.content);
							tmpList1.forEach(itm => {
								itm.goodsRdmUuid = itm.goodsDtlUuid || uuidv4();
								itm.checkResult = itm.checkResult || "false";
								itm.show = false;
								itm.swiperDisabled = false;
							});
							this.dataList = [...tmpList1, ];
							if (this.dataList.length > 0) {
								this.updatePreObj(this.dataList[this.dataList.length - 1]);
							} else {
								this.preObj = undefined;
							}
							this.canRollBack = false;
							this.$refs['mescrollRef0'].resetList(false);
						}, () => {
							uni.setStorageSync("showRollBackDataTip", '1');
						}, "恢复数据", "不再提示");
					}
				});
			},
			isDisable(d) {
				let ap = d.innerProductType != '01' && d.innerProductType != '02';
				console.log(d, '这是:' + ap);
				return ap;
			},
			getListHeight() {
				let s = "";
				// #ifndef H5-DINGDING
				s = (this.$u.sys().windowHeight - 50 - 60 - uni.upx2px(180) - uni.upx2px(60) - this.$u.sys()
					.statusBarHeight) + "px";
				// #endif
				// #ifdef H5-DINGDING
				s = (this.$u.sys().windowHeight - 50 - 60 - 44 - uni.upx2px(180) - uni.upx2px(60) - this.$u.sys()
					.statusBarHeight) + "px";
				// #endif
				return s;
			},
			getGoodSearchPopupHeight() {
				this.$u.getRect('.good-search-line').then(res => {
					this.searchGoodTop = res.bottom + "px";
					this.searchGoodHeight = (this.$u.sys().windowHeight - res.bottom - this.$u.sys()
						.statusBarHeight) + "px";
				});
			},
			getIndexByGoodsList(id) {
				for (let i = 0; i < this.realDataList.length; i++) {
					if (this.realDataList[i].goodsRdmUuid == id) {
						return this.realDataList.length - i;
					}
				}
				return -1;
			},
			rollBack() {
				goodsService.getGoodsDb(this.caseCode, this.user.user.personUuid).then(res => {
					if (res) {
						this.localData.content = res.content;
						this.localData.tid = res.tid;
						let tmpList1 = this.$u.deepClone(res.content);
						tmpList1.forEach(itm => {
							itm.goodsRdmUuid = itm.goodsDtlUuid || uuidv4();
							itm.checkResult = itm.checkResult || "false";
							itm.show = false;
							itm.swiperDisabled = false;
						});
						this.dataList = [...tmpList1, ];
						if (this.dataList.length > 0) {
							this.updatePreObj(this.dataList[this.dataList.length - 1]);
						} else {
							this.preObj = undefined;
						}
						this.canRollBack = false;
						this.$refs['mescrollRef0'].resetList(false);
					}
				});
			},
			setRightBtns() {
				// #ifdef H5-DINGDING
				if (this.canRollBack) {
					this.$deviceApi.setRight("恢复数据", () => {
						this.rollBack();
						this.setRightBtns();
					}, true, true);
				} else {
					this.$deviceApi.setRight("", () => {}, false, false);
				}
				// #endif
			},
			fabtrigger(btn) {
				if (btn.index == 0) {
					this.rollBack();
				}
			},
			init() {
				let self = this;
				this.getGoodSearchPopupHeight();
				uni.onWindowResize((res) => {
					if (this.defaultWindowHeight - res.size.windowHeight > 180) { // 阈值 超过这个值表示软键盘弹出了
						this.showSoftInputView = true;
					} else { // 否则软键盘收起了
						this.showSoftInputView = false;
						if (this.searchFlag) return;
						if (this.tmpChoice) {
							this.showSearchGoods = false;
							this.choiceGoodItem(this.tmpChoice);
							this.tmpChoice = undefined;
						}
					}
				});
			},
			updatePreObj(obj) {
				if (!obj) {
					this.preObj = undefined;
					return;
				}
				this.preObj = {
					unitQty: obj.unitQty,
					goodsType: obj.goodsType,
					toAddrName: obj.toAddrName,
					sourceAddrName: obj.sourceAddrName,
					propSubtype: obj.propSubtype || '',
					checkResult: obj.checkResult,
					getNode: obj.getNode,
					sourceAddr: obj.sourceAddr,
					toAddr: obj.toAddr,
				};
			},
			hasMustPreIsEmpty() {
				if (this.$u.test.isEmpty(this.preObj.unitQty) ||
					(this.$u.test.isEmpty(this.preObj.propSubtype) && this.hasShowChoicePropSubType(this.preObj.goodsType)) ||
					this.$u.test.isEmpty(this.preObj.getNode) ||
					this.$u.test.isEmpty(this.preObj.sourceAddr) ||
					this.$u.test.isEmpty(this.preObj.toAddr)
				) {
					console.log('上一条不完善信息：' + JSON.stringify(this.preObj));
					this.$modal.alert("请完善上一条物品的信息, 便于快速录入物品", () => {});
					return true;
				}
				return false;
			},
			updateGoodsDb() {
				this.localData.content = this.dataList;
				if (this.realDataList.length > 0) {
					this.updatePreObj(this.realDataList[0]);
				}
				goodsService.saveGoodsDb(this.localData).then(res => {
					console.log('保存成功');
					this.canRollBack = false;
					if (res) {
						this.localData.tid = res;
					}
				}).catch(e => {
					console.log('保存失败');
				});
			},
			searchBlur(e) {
				setTimeout(() => {
					console.log('==searchBlur==');
					if (!this.showSoftInputView && !this.searchFlag) {
						this.showSearchGoods = false;
					}
				}, 50);
			},
			touchStart(e) {
				console.log('==touchStart==');
				this.searchFlag = true;
			},
			touchEnd(e) {
				console.log('==touchEnd==');
				this.searchFlag = false;
			},
			searchFocus(e) {
				if (!this.$u.test.isEmpty(this.searchTxt)) {
					this.searchFlag = false;
					this.showSearchGoods = true;
				}
			},
			/*
			 * 条码查询
			 * */
			scanClick() {
				// #ifdef H5-DINGDING || H5-WECHAT
				this.$deviceApi.barCode().then(res => {
					this.$modal.showLoading("查询中...")
					caseService.searchByCode(res).then(
						res1 => {
							this.$modal.hideLoading();
							if (res1.success && res1.data && res1.data.length > 0) {
								this.addFrom = "scanBar";
								this.scanVal = res;
								if (res1.data.length == 1) {
									this.choiceGoodItem(res1.data[0]);
								} else {
									this.searchGoodList = [...res1.data, ];
									this.searchFlag = false;
									this.showSearchGoods = true;
								}
							} else {
								this.$u.toast('未查询到该物品');
							}
						}).catch(e => {
						this.$modal.hideLoading();
					});
				}).catch(err => {
					this.$u.toast('扫描失败');
				});
				// #endif
			},
			/**
			 * 扫码枪扫码
			 * @param {Object} ev
			 * @param {Object} str
			 */
			scanOther() {
				this.scanOtherData = {};
				this.scanOtherShow = !this.scanOtherShow;
				this.$el.querySelector('#scanOther input').setAttribute('inputmode', 'none');
				this.focus = !this.scanOtherShow;
				setTimeout(() => {
					this.$el.querySelector('#scanOther input').removeAttribute('inputmode');
				}, 100);
				this.searchTxt = "";
			},
			scanOtherInputEvent(e) {
				let tmpStr = e.detail.value;
				if (tmpStr.length < 13) return;
				tmpStr = tmpStr.substr(tmpStr.length - 13);
				caseService.searchByCode(tmpStr).then(
					res => {
						this.$modal.hideLoading();
						if (res.success && res.data && res.data.length > 0) {
							this.addFrom = "infraredScan";
							this.scanVal = tmpStr;
							if (res.data.length == 1) {
								this.choiceGoodItem(res.data[0]);
							} else {
								this.searchGoodList = [...res.data, ];
								this.searchFlag = false;
								this.showSearchGoods = true;
							}
						} else {
							this.$u.toast('未查询到该物品');
						}
					}).catch(e => {
					this.$modal.hideLoading();
				});
				this.$nextTick(function() {
					this.hideVal = '';
				});
			},
			hideMask() {
				this.scanOtherShow = false;
				this.hideVal = "";
			},
			inputGNameEvent(ev, str) {
				for (let i = 0; i < this.dataList.length; i++) {
					if (this.dataList[i].goodsRdmUuid == str) {
						try {
							this.dataList[i].goodsName = ev;
							this.updateGoodsDb();
						} catch (err) {
							console.log(err);
						}
						return;
					}
				}
			},
			inputQtyEvent(ev, str, needFixed) {
				console.log(this.dataList);
				for (let i = 0; i < this.dataList.length; i++) {
					if (this.dataList[i].goodsRdmUuid == str) {
						try {
							let n = this.dataList[i].qty * this.dataList[i].price;
							this.dataList[i].amt = Number(Number(n).toFixed(2));
							if (`${this.dataList[i].qty}`.indexOf('-') != -1) {
								this.dataList[i].qty = 0;
								this.dataList[i].amt = 0;
							}
							this.updateGoodsDb();
						} catch (err) {
							console.log(err);
						}
						return;
					}
				}
			},
			inputPriceEvent(ev, str) {
				for (let i = 0; i < this.dataList.length; i++) {
					if (this.dataList[i].goodsRdmUuid == str) {
						try {
							let n = this.dataList[i].qty * this.dataList[i].price;
							this.dataList[i].amt = Number(Number(n).toFixed(2));
							if (`${this.dataList[i].price}`.indexOf('-') != -1) {
								this.dataList[i].price = 0;
								this.dataList[i].amt = 0;
							}
							this.updateGoodsDb();
						} catch (err) {
							console.log(err);
						}
						return;
					}
				}
			},
			inputUnitEvent(ev, str) {
				for (let i = 0; i < this.dataList.length; i++) {
					if (this.dataList[i].goodsRdmUuid == str) {
						try {
							if (`${this.dataList[i].unitQty}`.indexOf('-') != -1) {
								this.dataList[i].unitQty = 0;
							}
						} catch (err) {
							console.log(err);
						}
						return;
					}
				}
			},
			choiceGoodItem(obj) {
				this.tmpChoice = undefined;
				this.searchFlag = false;
				this.searchTxt = '';
				if (!this.showSoftInputView) {
					this.showSearchGoods = false;
				} else {
					this.tmpChoice = obj;
					return;
				}
				if (this.preObj && this.hasMustPreIsEmpty()) {
					return;
				}
				this.$nextTick(function() {
					this.addNewItem(obj);
				})
			},
			updateDataContent(e) {
				for (let i = 0; i < this.dataList.length; i++) {
					if (this.dataList[i].goodsRdmUuid == e.goodsRdmUuid) {
						this.dataList[i].qty = Number(this.dataList[i].qty) + 1;
						this.dataList[i].amt = Number(Number(this.dataList[i].qty * this.dataList[i].price).toFixed(2));
						break;
					}
				}
				this.updateGoodsDb();
			},
			addNewItem(obj) {
				if (this.realDataList.length > 0) {
					this.updatePreObj(this.realDataList[0]);
				} else {
					if (this.dataList.length > 0) {
						this.updatePreObj(this.dataList[this.dataList.length - 1]);
					}
				}
				let tmp = {};
				if (this.preObj) tmp = this.$u.deepClone(this.preObj);
				tmp.goodsRdmUuid = uuidv4(); // 前端页面用到
				// tmp.caseUuid = this.caseUuid;
				tmp.goodsTypeName = this.getDicName(this.$u.dic.DIC_KEYS.CIGA, obj.productType);
				// 改为如果上一个的物品类型和本次添加的物品类型一致则保留，否则物品性质置空
				if (obj.productType != tmp.goodsType) {
					tmp.propSubTypeName = '';
					tmp.propSubtype = '';
				}
				// // 新加卷烟或电子烟物品时，物品性质要置空掉
				// if (obj.productType.substr(0, 1) == "1") {
				//   if (Number(tmp.propSubtype) >= 21) {
				//     tmp.propSubTypeName = '';
				//     tmp.propSubtype = '';
				//   }else{
				//     tmp.propSubTypeName = this.getDicName(this.$u.dic.DIC_KEYS.GOODS_PROP_SUBTYPE, tmp.propSubtype);      //   }
				// } else if (obj.productType.substr(0, 1) == "7") {
				//   if (Number(tmp.propSubtype) < 21) {
				//     tmp.propSubTypeName = '';
				//     tmp.propSubtype = '';
				//   }else{
				//     tmp.propSubTypeName = this.getDicName(this.$u.dic.DIC_KEYS.GOODS_PROP_SUBTYPE, tmp.propSubtype);
				//   }
				// }
				tmp.getNodeName = this.getDicName(this.$u.dic.DIC_KEYS.GET_NODE, tmp.getNode);
				tmp.goodsType = obj.productType;
				tmp.goodsUuid = obj.productUuid;
				this.$set(tmp, 'goodsName', obj.productName);
				tmp.stripCode = obj.stripCode;
				tmp.innerProductType = obj.innerProductType;
				tmp.spec = obj.spec;
				tmp.checkResult = "false";
				tmp.unit = obj.defaultUnitName || '条'; // 默认给个条，不要让数据为空
				tmp.price = obj.rtlPr || 0;
				tmp.unitQty = obj.defaultUnitQty;
				if (this.addFrom == 'scanBar' || this.addFrom == 'infraredScan') {
					if (this.scanVal != undefined && this.scanVal == obj.packCode) {
						tmp.qty = 0.1; // 包码 返回0.1条
					} else if (this.scanVal != undefined && this.scanVal == obj.partCode) {
						tmp.qty = 50; // 一件=50条
					} else { // 条码
						tmp.qty = 1;
					}
				} else {
					tmp.qty = 1;
				}

				try {
					let n = tmp.qty * tmp.price;
					tmp.amt = Number(Number(n).toFixed(2));
				} catch (e) {
					console.log(e);
					tmp.amt = 0;
				}
				tmp.show = false;
				tmp.swiperDisabled = false;
				this.dataList.push(tmp);
				this.$set(this.dataList[this.dataList.length - 1], 'goodsName', obj.productName);
				this.updateGoodsDb();
				this.$refs['mescrollRef0'].resetList(false);
			},
			getDicName(keyword, code) {
				return this.$u.dic.getDicNameByKeyCode(keyword, code);
			},
			getSearchGoodList() {
				if (this.$u.test.isEmpty(this.searchTxt)) return;
				caseService.searchPro(this.$u.test.isEmpty(this.searchTxt) ? undefined : this.searchTxt, 1, 20).then(
					res => {
						if (res.success) {
							this.addFrom = "search";
							this.scanVal = undefined;
							if (res.data.length == 1) {
								this.choiceGoodItem(res.data[0]);
							} else if (res.data.length > 1) {
								this.searchGoodList = [...res.data, ];
								this.searchFlag = false;
								this.showSearchGoods = true;
							}
						}
					});
			},
			mergeData(cb) {
				this.$modal.showLoading('正在合并数据...');
				let p = new Promise((resolve, reject) => {
					let tmpList = this.$u.deepClone(this.dataList);
					let mergeObj = {};
					tmpList.forEach(itm => {
						// goodsRegUuid 加上的原因是 有值表示该数据一被使用不能再操作了
						let keys = itm.unitQty + '&' + itm.goodsName + '&' + itm.goodsUuid + '&' + itm.unit + '&' + itm.price +
							'&' + itm.sourceAddr + '&' + itm.toAddr + '&' + itm
							.getNode + '&' + itm.propSubtype + '&' + itm.goodsRegUuid + '&' + itm
							.checkResult;
						if (mergeObj[keys]) {
							let tmp = mergeObj[keys];
							tmp.push(itm);
						} else {
							let tmp = [];
							tmp.push(itm);
							mergeObj[keys] = tmp;
						}
					});
					let newGoodList = [];
					try {
						for (let k in mergeObj) {
							let ar = mergeObj[k];
							let op;
							for (let i = 0; i < ar.length; i++) {
								if (i == 0) {
									op = ar[i];
									try {
										op.qty = Number(op.qty);
										op.price = Number(op.price);
									} catch (er) {
										op.qty = 0;
										op.price = 0;
									}
								} else {
									try {
										op.qty += Number(ar[i].qty);
										op.amt = op.qty * Number(op.price);
									} catch (er) {
										op.qty = 0;
										op.amt = 0;
									}
								}
							}
							if (op) newGoodList.push(op);
						}
					} catch (e) {
						console.log(e);
						newGoodList = [];
					}
					resolve(newGoodList);
				});
				p.then(res => {
					this.$modal.hideLoading();
					if (res.length == 0 && this.dataList.length > 0) {
						// 则表示合并出错了
						this.$u.toast('合并出错了');
						return;
					}
					this.dataList = [...res, ];
					this.updateGoodsDb();
					cb && cb();
				});
			},
			confirm: function() {
				if (this.realDataList.length > 0) {
					for (let i = 0; i < this.realDataList.length; i++) {
						let tmp = this.realDataList[i];
						if (this.$u.test.isEmpty(tmp.unitQty) ||
							(this.$u.test.isEmpty(tmp.propSubtype) && this.hasShowChoicePropSubType(tmp.goodsType)) ||
							this.$u.test.isEmpty(tmp.getNode) ||
							this.$u.test.isEmpty(tmp.sourceAddr) ||
							this.$u.test.isEmpty(tmp.toAddr) ||
							this.$u.test.isEmpty(tmp.amt) ||
							this.$u.test.isEmpty(tmp.price) ||
							this.$u.test.isEmpty(tmp.unit) ||
							this.$u.test.isEmpty(tmp.qty)
						) {
							console.log('空数据:' + JSON.stringify(tmp));
							this.$modal.alert(`【数据${this.realDataList.length - i} ${tmp.goodsName}】记录有数据为空？`);
							return;
						} else {
							// 卷烟或电子烟类型选择的物品性质校验
							if (tmp.goodsType.substr(0, 1) == "1") {
								if (Number(tmp.propSubtype) >= 21) {
									this.$modal.alert(`【数据${this.realDataList.length - i} ${tmp.goodsName}】请选择正确的物品性质！`);
									return false
								}
							} else if (tmp.goodsType.substr(0, 1) == "7") {
								if (Number(tmp.propSubtype) < 21) {
									this.$modal.alert(`【数据${this.realDataList.length - i} ${tmp.goodsName}】请选择正确的物品性质！`);
									return false
								}
							}
						}
					}
					this.mergeData(() => {
						this.saveGoods();
					});
				} else {
					// this.$u.toast("请先添加物品！");
					// return;
					this.saveGoods();
				}
			},
			saveGoods() {
				this.$modal.showLoading("正在保存...");
				// 新增保存都是保存自己的数据
				caseService.saveGoodsInfo(this.caseUuid, '0', this.dataList).then(res => {
					this.$modal.hideLoading();
					if (res.success) {
						// this.$u.toast('保存成功');
						goodsService.delGoodsDb(this.caseCode, this.user.user.personUuid);
						this.canRollBack = false;
						this.backPrev({
							paramKey: "refresh",
							param: true,
						});
					} else {
						console.log("保存错误日志:" + res.msg);
						this.$modal.alert(
							"保存失败:" + res.msg,
							"提示", () => {}, );
					}
				}).catch(err => {
					this.$modal.hideLoading();
					this.$modal.alert("保存失败:" + err);
				});
			},
			loadData(page, isNeedRefresh, isSplice) {
				return new Promise((resolve, reject) => {
					if (this.realDataList.length > (page.size * (page.num - 1))) {
						let s = (page.size * (page.num - 1));
						let len = this.realDataList.length - s;
						if (len > page.size) {
							resolve({
								data: this.realDataList.slice(s, s + page.size),
								totalCount: this.realDataList.length,
							});
						} else {
							if (isSplice) { // 主动拼接上一页的数据 补足limit
								let lep = page.size - (this.realDataList.length - s);
								resolve({
									data: [...this.realDataList.slice(s - lep, s), ...this.realDataList.slice(s), ],
									totalCount: this.realDataList.length,
									isSplice: isSplice,
								});
							} else {
								resolve({
									data: this.realDataList.slice(s),
									totalCount: this.realDataList.length,
								});
							}
						}
					} else {
						resolve({
							data: [],
							totalCount: 0,
						});
					}
				});
			},
			dicSelectOpen: function(keyWord) {
				if (this.dicKeyWords == keyWord && this.dicShow) {
					return true;
				}
				return false;
			},
			showDic: function(key, cur, id) {
        console.log('key', key)
        console.log('cur', cur)
        console.log('id', id)
				if (this.dicShow) return;
				this.dicKeyWords = key;
				this.dicCurrentSelect = cur;
				this.dicShow = true;
				this.currIndex = id;
			},
			extFilterFun(itm, keyWords) {
				if (keyWords == this.$u.dic.DIC_KEYS.GOODS_PROP_SUBTYPE) {
					let obj;
					let tmpList = this.realDataList.filter(itm => {
						if (itm.goodsRdmUuid == this.currIndex) return true;
						return false;
					});
					if (tmpList.length > 0) {
						obj = tmpList[0];
					}
					if (obj == undefined) return true;
					let arr = getPropSubtypesByBrandSubType(obj.goodsType);
					return arr.filter(ip => ip.id == itm.bcbCode).length > 0;
				}
				return true;
			},
			selectDicConfirm: function(e) {
				let obj;
				let tmpList = this.realDataList.filter(itm => {
					if (itm.goodsRdmUuid == this.currIndex) return true;
					return false;
				});
				if (tmpList.length > 0) {
					obj = tmpList[0];
				}
				if (obj == undefined) return;
				if (this.dicKeyWords == this.$u.dic.DIC_KEYS.GOODS_PROP_SUBTYPE) {
					obj.propSubTypeName = e[0].label;
					obj.propSubtype = e[0].extra.bcbCode;
				} else if (this.dicKeyWords == this.$u.dic.DIC_KEYS.GET_NODE) {
					obj.getNodeName = e[0].label;
					obj.getNode = e[0].extra.bcbCode
				}
				this.updateGoodsDb();
			},
			// 来源地
			choiceAutoItem(itm, rdmId) {
				let obj;
				for (let i = 0; i < this.dataList.length; i++) {
					if (this.dataList[i].goodsRdmUuid == rdmId) {
						obj = this.dataList[i];
						break;
					}
				}
				if (obj == undefined) return;
				this.$set(obj, "sourceAddr", itm.areaCode);
				if (this.$modal.isMuniCity(itm.procode)) {
					this.$set(obj, "sourceAddrName", [itm.admdivname, itm.countryname, ].join(""));
				} else {
					this.$set(obj, "sourceAddrName", [itm.proname, itm.admdivname, itm.countryname, ].join(""));
				}
				this.updateGoodsDb();
			},
			// 去向地
			choiceAutoItem1(itm, rdmId) {
				let obj;
				for (let i = 0; i < this.dataList.length; i++) {
					if (this.dataList[i].goodsRdmUuid == rdmId) {
						obj = this.dataList[i];
						break;
					}
				}
				if (obj == undefined) return;
				this.$set(obj, "toAddr", itm.areaCode);
				if (this.$modal.isMuniCity(itm.procode)) {
					this.$set(obj, "toAddrName", [itm.admdivname, itm.countryname, ].join(""));
				} else {
					this.$set(obj, "toAddrName", [itm.proname, itm.admdivname, itm.countryname, ].join(""));
				}
				this.updateGoodsDb();
			},
			vaildChoice(val, id) {
				let obj;
				for (let i = 0; i < this.dataList.length; i++) {
					if (this.dataList[i].goodsRdmUuid == id) {
						obj = this.dataList[i];
						break;
					}
				}
				if (obj == undefined) return;
				// 修改点击来源地之后 再点击其他地方 来源地被清空 fsx 2024-1-9 开始
				if(this.$u.test.isEmpty(obj.sourceAddr)){
					this.$set(obj, "sourceAddrName", "");
				}
				// 修改点击来源地之后 再点击其他地方 来源地被清空 fsx 2024-1-9 结束
			},
			vaildChoice1(val, id) {
				let obj;
				for (let i = 0; i < this.dataList.length; i++) {
					if (this.dataList[i].goodsRdmUuid == id) {
						obj = this.dataList[i];
						break;
					}
				}
				if (obj == undefined) return;
				// 修改点击来源地之后 再点击其他地方 来源地被清空 fsx 2024-1-9 开始
				if(this.$u.test.isEmpty(obj.toAddr)){
					this.$set(obj, "toAddrName", "");
				}
				// 修改点击来源地之后 再点击其他地方 来源地被清空 fsx 2024-1-9 结束
			},
			searchData(txt) {
				return new Promise((resolve, reject) => {
					if (this.$u.test.isEmpty(txt)) {
						resolve([]);
						return;
					}
					commonService.queryAreaBaseList(txt).then(res => {
						if (res.success) {
							let tmp = res.data;
							tmp.forEach(itm => {
								itm.name = [itm.proname, itm.admdivname, itm.countryname, ].join("");
								itm.id = uuidv4();
							});
							resolve(tmp);
						} else {
							resolve([]);
						}
					}).catch(err => {
						resolve([]);
					});
				});
			},
			// index1是数据索引 index是导航索引
			swiperClick(index1, index) {
				let cur = -1;
				for (let i = 0; i < this.dataList.length; i++) {
					if (this.dataList[i].goodsRdmUuid == index1) {
						cur = i;
						break;
					}
				}
				if (cur == -1) {
					this.$u.toast("选中数据无效");
					return;
				}
				if (index == 0) {
					this.dataList.map((val, idx) => {
						this.dataList[idx].show = false;
					});
					this.dataList.splice(cur, 1);
					if (this.dataList.length == 0) {
						this.updatePreObj();
					} else {
						this.updatePreObj(this.dataList[this.dataList.length - 1]);
					}
					this.$refs['mescrollRef0'].resetList(false);
				}
			},
			swiperOpen(index) {
				this.dataList.map((val, idx) => {
					this.dataList[idx].show = index == val.goodsRdmUuid;
				});
			},
		},
	}
</script>
<style lang="scss" scoped>
	@import "../case_common.scss";

	.page {
		padding: 0;
	}

	uni-page-body {
		height: 100%;
	}

	.nav-right-icon {
		margin-right: 30rpx;
		font-size: .8rem;
		color: #FFF;
	}

	.sub-title-lay {
		height: 60px;

		.sub-title {
			font-size: 28rpx;
			color: $u-tips-color;
		}

		text {
			font-size: 36rpx;
			font-weight: bold;
		}
	}

	.search-lay {
		height: 50px;

		.search-title {
			font-size: 32rpx;
			font-weight: 500;
			padding-right: 30rpx;
		}

	}

	.flat-bottom {
		position: fixed;
		bottom: 0;
		margin: auto;
		z-index: 88;
		height: 180rpx;
		left: 0;
		right: 0;
		background-color: white;
	}

	.flat-line {
		margin-top: 10rpx;
		margin-bottom: 10rpx;
	}

	.num-lay {
		height: 40px;
		display: flex;
		flex-direction: row;
		justify-content: flex-start;
		align-items: center;
		margin-top: 10px;
	}

	.num-title {
		border-radius: 50%;
		background-color: $u_border_color;
		width: 40rpx;
		height: 40rpx;
		line-height: 40rpx;
		text-align: center;
		margin: 0 20rpx 0 10rpx;
	}

	.num-content {
		color: #222;
		font-size: .8rem;
		font-weight: bold;
	}

	.pty-lay {
		display: flex;
		flex-direction: row;
		align-items: center;
		padding: 10rpx 10rpx;
		// margin: 0rpx 20rpx;
		border-bottom: 1px solid $u-border-color;
	}

	.price-lay {
		display: flex;
		flex-direction: row;
		align-items: center;
		padding: 10rpx 10rpx;
		margin: 0rpx 10rpx;
		border-bottom: 1px solid $u-border-color;
	}

	.pop-content {
		padding: 24rpx;
		touch-action: none;
	}

	.m-input {
		margin: 0 10rpx;
	}

	.pop-item {
		font-size: 14px;
		padding: 10px 10px;
		border-bottom: 1rpx solid #EEEEEE;
	}

	.good-search-lay {
		width: 100%;
		margin-left: -30rpx;
		z-index: 199;
		position: absolute;
		background-color: white;
	}

	.warp {
		font-size: 40rpx;
		color: white;
		font-weight: bold;
		display: flex;
		justify-content: center;
		align-self: center;
		height: 100%;
		flex-direction: column;
	}

	.tp-class {
		width: 100%;
	}

	.lay-item {
		width: calc(100% - 5px);
	}

	/deep/.u-swipe-action {
		overflow: visible;
	}
</style>
